import * as lib from '../../../components/aotoo/lib/index'
import {getYmd, lunar} from '../../../components/modules/calendar/index'

const caseHooks = lib.hooks('calender-record-work', true)

// 下一周期差几天
export function diffCycleDays(oriDate, today, params={}){
  const step = params.step || 'month'   // year month cycle:number  cycle为自定义周期
  const daystamp = 24 * 60 * 60 * 1000
  let remainder = (oriDate.timestamp - today.timestamp) % daystamp
  remainder = remainder > 0 ? 1 : remainder < 0 ? -1 : 0
  let diffDays = (oriDate.timestamp - today.timestamp) / daystamp + remainder
  let nextDate = null

  if (diffDays < 0) {
    if (step === 'month') {
      const targetDate = getYmd(`${today.year}-${today.month}-${oriDate.day}`)
      remainder = (targetDate.timestamp - today.timestamp) % daystamp
      diffDays = (targetDate.timestamp - today.timestamp) / daystamp + remainder
      nextDate = getYmd(`${today.year}-${today.month+1}-${oriDate.day}`)
      if (diffDays < 0) {
        remainder = (nextDate.timestamp - today.timestamp) % daystamp
        diffDays = (nextDate.timestamp - today.timestamp) / daystamp + remainder
      }
    }

    if (step === 'year') {
      const targetDate = getYmd(`${today.year}-${oriDate.month}-${oriDate.day}`)
      remainder = (targetDate.timestamp - today.timestamp) % daystamp
      diffDays = (targetDate.timestamp - today.timestamp) / daystamp + remainder
      nextDate = getYmd(`${today.year+1}-${oriDate.month}-${oriDate.day}`)
      if (diffDays < 0) {
        remainder = (nextDate.timestamp - today.timestamp) % daystamp
        diffDays = (nextDate.timestamp - today.timestamp) / daystamp + remainder
      }
    }

    // 自定义周期
    if (typeof step === 'number') {
      let tempDays = Math.abs(diffDays)
      tempDays = tempDays % step
      if (tempDays) {
        const count = parseInt(tempDays/step)+1
        diffDays = count*step - tempDays
      }
    }
  }

  return {
    diffDays,
    nextDate
  }
}


export function getMarkDates(){
  const cycleDates = []
  const accessKey = ['commemorate', 'reciprocal', 'memo', 'menstruation']
  const res = (caseHooks.getList() || []).sort((a,b)=>b.createtime-a.createtime)
  const temp = res.filter( caseItem => {
    const ky = caseItem.key.split('_')[0]
    return accessKey.includes(ky)
  })

  temp.forEach(caseItem=>{
    const ky = caseItem.key.split('_')[0]
    let   caseDate = getYmd(caseItem.value.date)
    caseDate.className = caseItem.value.itemClass

    if (ky === 'memo' && caseItem.value.hideDate) {
      caseDate = null
    }

    // 经期
    if (caseItem.key === 'menstruation') {
      caseDate.interval = caseItem.value.interval
    }

    caseDate && cycleDates.push(caseDate)
  })

  // 薪水日
  const salaryData = caseHooks.getItem('salary')
  if (salaryData) {
    const salaryDate = getYmd(salaryData.date)
    salaryDate.salaryDay = salaryDate.month+'-'+salaryDate.day
    salaryDate.className = 'salary'
    cycleDates.push(salaryDate)
  }
  return cycleDates
}